package com.example.qiandao.service;

import com.example.qiandao.controller.responsedto.CheckinRecordDTO;
import com.example.qiandao.entity.CheckinRecord;
import com.example.qiandao.repository.CheckinRecordRepository;
import com.example.qiandao.repository.CheckinStateRepository;
import com.example.qiandao.repository.ClazzRepository;
import com.example.qiandao.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CheckinRecordService {
    @Autowired
    private CheckinRecordRepository checkinRecordRepository;

    @Autowired
    private CheckinStateRepository checkinStateRepository;

    @Autowired
    private ClazzRepository clazzRepository;

    @Autowired
    private CourseRepository courseRepository;

    /**
     * 根据 CheckinHistory 的 id 获取所有学生的签到记录
     *
     * @param checkinHistoryId 签到历史记录的 id
     * @return 包含签到记录的 DTO 列表
     */
    public List<CheckinRecordDTO> getCheckinRecordsByHistoryId(Long checkinHistoryId) {
        List<CheckinRecord> records = checkinRecordRepository.findByCheckinHistoryId(checkinHistoryId);
        return records.stream().map(record -> {
            CheckinRecordDTO dto = new CheckinRecordDTO();
            dto.setStudentId(record.getStudent().getId());
            dto.setStudentName(record.getStudent().getName());
            dto.setCheckinStateName(record.getCheckinState().getStateName());
            dto.setCheckinTime(record.getStudentCheckinTime());
            dto.setCheckinStateId(record.getCheckinState().getState());
            return dto;
        }).toList();
    }

    /**
     * 根据 userId 和新的签到状态 ID 更新签到记录的状态
     *
     * @param userId         学生的 ID
     * @param newCheckinStateId 新的签到状态 ID
     * @return 是否更新成功
     */
    public boolean updateCheckinState(Long userId, Integer newCheckinStateId, Long checkinHistoryId) {
        CheckinRecord record = checkinRecordRepository.findByStudentIdAndCheckinHistoryId(userId, checkinHistoryId);
        if (record != null) {
            record.setCheckinState(checkinStateRepository.findById(newCheckinStateId).get());
            checkinRecordRepository.save(record);
            return true;
        }
        return false;
    }

    public List<CheckinRecordDTO> getCheckinRecordByStudentIdAndClassId(Long studentId, Long classId) {
        List<CheckinRecord> records = checkinRecordRepository.findByStudentIdAndClassId(studentId, classId);
        return records.stream().map(record -> {
            CheckinRecordDTO dto = new CheckinRecordDTO();
            dto.setStudentId(record.getStudent().getId());
            dto.setStudentName(record.getStudent().getName());
            dto.setCheckinStateName(record.getCheckinState().getStateName());
            dto.setCheckinTime(record.getStudentCheckinTime());
            dto.setCheckinStateId(record.getCheckinState().getState());
            return dto;
        }).toList();
    }
}